package com.czk.socket;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 网络socket传输的nio
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/10 12:05
 */
public class NonBlockingNioTest {
    @Test
    public void client() throws Exception {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        // 切换成非阻塞
        socketChannel.configureBlocking(false);
        // 指定缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 发送数据给服务器
        byteBuffer.put("dsdasdas".getBytes());
        //
        byteBuffer.flip();
        // 写数据
        socketChannel.write(byteBuffer);
        byteBuffer.clear();
        // 关闭通道
        socketChannel.close();
    }

    @Test
    public void server() throws Exception {
        // 获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 切换成非阻塞
        serverSocketChannel.configureBlocking(false);
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(9898));
        // 获取选择器
        Selector selector = Selector.open();
        // 将通道注册到选择器 并且指定监听事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // l轮询获取选择器上已经准备就绪的时间
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 如果是接收状态
                if (selectionKey.isAcceptable()) {
                    // 获取客户端的连接
                    SocketChannel accept = serverSocketChannel.accept();
                    // 将其切换成非阻塞模式
                    accept.configureBlocking(false);
                    // 将该通道注册到选择器上
                    accept.register(selector, SelectionKey.OP_READ);

                } else if (selectionKey.isReadable()) {
                    // 获取当前选择器上的读就绪的通道
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    // 读取数据
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = channel.read(byteBuffer)) != -1) {
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(), 0, len));
                        byteBuffer.clear();
                    }
                }
                // 取消选择器
                iterator.remove();
            }
        }
    }
}
